package com.basic.modules.ykf.controller;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.basic.common.annotation.StringTrim;
import com.basic.common.exception.RRException;
import com.basic.common.utils.PageUtils;
import com.basic.common.utils.ParamsModel;
import com.basic.common.utils.R;
import com.basic.modules.sys.controller.AbstractController;
import com.basic.modules.ykf.dao.YkfAccountInputRecordDao;
import com.basic.modules.ykf.entity.YkfAccountInputRecordEntity;
import com.basic.modules.ykf.entity.YkfCustomerConsultEntity;
import com.basic.modules.ykf.entity.YkfCustomerEntity;
import com.basic.modules.ykf.entity.YkfCustomerShopEntity;
import com.basic.modules.ykf.model.Statistics2Model;
import com.basic.modules.ykf.model.Statistics3Model;
import com.basic.modules.ykf.model.YkfStatisticsModel;
import com.basic.modules.ykf.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 统计
 *
 * @author maoheng
 * @email 15738859597@163.com
 * @date 2024-04-06 18:40:44
 */
@RestController
@RequestMapping("ykf/statistics")
public class YkfStatisticsController extends AbstractController {

    @Autowired
    private YkfCustomerService ykfCustomerService;

    @Autowired
    private YkfCustomerShopService ykfCustomerShopService;

    @Autowired
    private YkfAccountInputRecordDao inputRecordDao;

    @Autowired
    private YkfCustomerConsultService consultService;


    /**
     * 客户统计
     */
    @PostMapping("/statistics1")
    public R statistics1() {
        List<Map<String, Object>> maps = new ArrayList<>();
        Map<String, Object> map1 = new HashMap<>();
        map1.put("name", "合作中的客户数");
        map1.put("value", 0);
        Map<String, Object> map2 = new HashMap<>();
        map2.put("name", "合作中的店铺数");
        map2.put("value", 0);
        Map<String, Object> map3 = new HashMap<>();
        map3.put("name", "总服务店铺数");
        map3.put("value", 0);
        Map<String, Object> map4 = new HashMap<>();
        map4.put("name", "客户流失数");
        map4.put("value", 0);
        Map<String, Object> map5 = new HashMap<>();
        map5.put("name", "年度销售额");
        map5.put("value", 0);
        //查询所有店铺
        List<YkfCustomerShopEntity> list = ykfCustomerShopService.list();
        if (ObjectUtil.isNotEmpty(list)) {
            long count1 = list.stream().filter(o -> o.getCooperateStatus() == 1).map(YkfCustomerShopEntity::getCustomerId).distinct().count();
            map1.put("value", count1);
            long count2 = list.stream().filter(o -> o.getCooperateStatus() == 1).map(YkfCustomerShopEntity::getShopId).distinct().count();
            map2.put("value", count2);
            long count3 = list.stream().map(YkfCustomerShopEntity::getShopId).distinct().count();
            map3.put("value", count3);

//            List<Long> customerIds = list.stream().filter(o -> o.getCooperateStatus() == 1).map(YkfCustomerShopEntity::getCustomerId).distinct().collect(Collectors.toList());
//            List<Long> stopCustomerIds = list.stream().filter(o -> o.getCooperateStatus() == 0).map(YkfCustomerShopEntity::getCustomerId).distinct().collect(Collectors.toList());
//            if (ObjectUtil.isNotEmpty(stopCustomerIds)) {
//                int value4 = stopCustomerIds.size();
//                for (Long stopCustomerId : stopCustomerIds) {
//                    if (customerIds.contains(stopCustomerId)) {
//                        value4 --;
//                    }
//                }
//                map4.put("value", value4);
//            }
        }

        QueryWrapper<YkfCustomerEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(YkfCustomerEntity::getCooperateStatus, "0");
        int count = ykfCustomerService.count(queryWrapper);
        map4.put("value", count);

        //查询年度销售额
        DateTime dateTime = DateUtil.beginOfYear(DateUtil.date());
        QueryWrapper<YkfAccountInputRecordEntity> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.lambda().ge(YkfAccountInputRecordEntity::getDate, dateTime);
        queryWrapper1.select("sum(sales_revenue) as salesRevenue");
        Map<String, Object> map = inputRecordDao.selectMaps(queryWrapper1).get(0);
        if (ObjectUtil.isNotEmpty(map)) {
            map5.put("value", map.get("salesRevenue"));
        }

        maps.add(map1);
        maps.add(map2);
        maps.add(map3);
        maps.add(map4);
        maps.add(map5);
        return R.ok(maps);
    }

    @StringTrim
    @PostMapping("/statistics2")
    public R statistics2(@RequestBody YkfStatisticsModel statisticsModel) {
        if (ObjectUtil.isEmpty(statisticsModel) || StrUtil.isBlank(statisticsModel.getSearchType())) {
            throw new RRException("参数缺失");
        }
        //查询所有店铺
        QueryWrapper<YkfCustomerShopEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(YkfCustomerShopEntity::getCooperateStatus, "1");
        List<YkfCustomerShopEntity> list = ykfCustomerShopService.list(queryWrapper);
        if (ObjectUtil.isEmpty(list)) {
            return R.ok(new ArrayList<>());
        }
        List<Statistics2Model> resList = new ArrayList<>();
        switch (statisticsModel.getSearchType()) {
            case "1":
                Map<String, List<YkfCustomerShopEntity>> collect1 = list.stream().collect(Collectors.groupingBy(o -> StrUtil.isBlank(o.getPlatformName()) ? "" : o.getPlatformName()));
                for (String key : collect1.keySet()) {
                    if (StrUtil.isNotBlank(key)) {
                        Statistics2Model model = new Statistics2Model();
                        model.setLabel(key);
                        model.setValue(new BigDecimal(collect1.get(key).size()));
                        BigDecimal decimal1 = new BigDecimal(collect1.get(key).size());
                        BigDecimal decimal2 = new BigDecimal(list.size());
                        model.setProportion(decimal1.multiply(new BigDecimal(100)).divide(decimal2, 2, RoundingMode.HALF_UP));
                        resList.add(model);
                    }
                }
                break;
            case "2":
                Map<String, List<YkfCustomerShopEntity>> collect2 = list.stream().collect(Collectors.groupingBy(o -> StrUtil.isBlank(o.getShopTypeName()) ? "" : o.getShopTypeName()));
                for (String key : collect2.keySet()) {
                    if (StrUtil.isNotBlank(key)) {
                        Statistics2Model model = new Statistics2Model();
                        model.setLabel(key);
                        model.setValue(new BigDecimal(collect2.get(key).size()));
                        BigDecimal decimal1 = new BigDecimal(collect2.get(key).size());
                        BigDecimal decimal2 = new BigDecimal(list.size());
                        model.setProportion(decimal1.multiply(new BigDecimal(100)).divide(decimal2, 2, RoundingMode.HALF_UP));
                        resList.add(model);
                    }
                }
                break;
            case "3":
                Map<String, List<YkfCustomerShopEntity>> collect3 = list.stream().collect(Collectors.groupingBy(o -> StrUtil.isBlank(o.getCustomTypeName()) ? "" : o.getCustomTypeName()));
                for (String key : collect3.keySet()) {
                    if (StrUtil.isNotBlank(key)) {
                        Statistics2Model model = new Statistics2Model();
                        model.setLabel(key);
                        model.setValue(new BigDecimal(collect3.get(key).size()));
                        BigDecimal decimal1 = new BigDecimal(collect3.get(key).size());
                        BigDecimal decimal2 = new BigDecimal(list.size());
                        model.setProportion(decimal1.multiply(new BigDecimal(100)).divide(decimal2, 2, RoundingMode.HALF_UP));
                        resList.add(model);
                    }
                }
                break;
            case "4":
                Map<String, List<YkfCustomerShopEntity>> collect4 = list.stream().collect(Collectors.groupingBy(o -> StrUtil.isBlank(o.getServiceShiftName()) ? "" : o.getServiceShiftName()));
                for (String key : collect4.keySet()) {
                    if (StrUtil.isNotBlank(key)) {
                        Statistics2Model model = new Statistics2Model();
                        model.setLabel(key);
                        model.setValue(new BigDecimal(collect4.get(key).size()));
                        BigDecimal decimal1 = new BigDecimal(collect4.get(key).size());
                        BigDecimal decimal2 = new BigDecimal(list.size());
                        model.setProportion(decimal1.multiply(new BigDecimal(100)).divide(decimal2, 2, RoundingMode.HALF_UP));
                        resList.add(model);
                    }
                }
                break;
            case "5":
                Map<String, List<YkfCustomerShopEntity>> collect5 = list.stream().collect(Collectors.groupingBy(o -> StrUtil.isBlank(o.getMarketTypeName()) ? "" : o.getMarketTypeName()));
                for (String key : collect5.keySet()) {
                    if (StrUtil.isNotBlank(key)) {
                        Statistics2Model model = new Statistics2Model();
                        model.setLabel(key);
                        model.setValue(new BigDecimal(collect5.get(key).size()));
                        BigDecimal decimal1 = new BigDecimal(collect5.get(key).size());
                        BigDecimal decimal2 = new BigDecimal(list.size());
                        model.setProportion(decimal1.multiply(new BigDecimal(100)).divide(decimal2, 2, RoundingMode.HALF_UP));
                        resList.add(model);
                    }
                }
                break;
            case "6":
                Map<String, List<YkfCustomerShopEntity>> collect6 = list.stream().collect(Collectors.groupingBy(o -> StrUtil.isBlank(o.getExpandTypeName()) ? "" : o.getExpandTypeName()));
                for (String key : collect6.keySet()) {
                    if (StrUtil.isNotBlank(key)) {
                        Statistics2Model model = new Statistics2Model();
                        model.setLabel(key);
                        model.setValue(new BigDecimal(collect6.get(key).size()));
                        BigDecimal decimal1 = new BigDecimal(collect6.get(key).size());
                        BigDecimal decimal2 = new BigDecimal(list.size());
                        model.setProportion(decimal1.multiply(new BigDecimal(100)).divide(decimal2, 2, RoundingMode.HALF_UP));
                        resList.add(model);
                    }
                }
                break;
            case "7":
                Map<String, List<YkfCustomerShopEntity>> collect7 = list.stream().collect(Collectors.groupingBy(o -> StrUtil.isBlank(o.getArea()) ? "-" : StrUtil.split(o.getArea(), '-').get(0)));
                for (String key : collect7.keySet()) {
                    if (StrUtil.isNotBlank(key)) {
                        Statistics2Model model = new Statistics2Model();
                        model.setLabel(key);
                        model.setValue(new BigDecimal(collect7.get(key).size()));
                        BigDecimal decimal1 = new BigDecimal(collect7.get(key).size());
                        BigDecimal decimal2 = new BigDecimal(list.size());
                        model.setProportion(decimal1.multiply(new BigDecimal(100)).divide(decimal2, 2, RoundingMode.HALF_UP));
                        resList.add(model);
                    }
                }
                break;
        }
        resList.sort(Comparator.comparing(Statistics2Model::getProportion).reversed());
        return R.ok(resList);
    }

    /**
     * 新增客户
     */
    @StringTrim
    @PostMapping("/statistics3")
    public R statistics3(@RequestBody YkfStatisticsModel req) {
        List<Statistics3Model> resList = new ArrayList<>();
        if (ObjectUtil.isNotEmpty(req) && ObjectUtil.isNotEmpty(req.getDateStart()) && ObjectUtil.isNotEmpty(req.getDateEnd())) {
            QueryWrapper<YkfCustomerEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().ge(YkfCustomerEntity::getCreateTime, req.getDateStart())
                    .le(YkfCustomerEntity::getCreateTime, req.getDateEnd());
            int count = ykfCustomerService.count(queryWrapper);
            Statistics3Model model = new Statistics3Model();
            model.setDate(DateUtil.formatDate(req.getDateStart()) + " 至 " + DateUtil.formatDate(req.getDateEnd()));
            model.setValue(new BigDecimal(count));
            resList.add(model);
        } else {
            String queryCycleType = req.getQueryCycleType();
            if (StrUtil.isBlank(queryCycleType)) {
                queryCycleType = "1";
            }
            if (StrUtil.equals(queryCycleType, "1")) {
                //近30天
                DateTime endDate = DateUtil.date();
                DateTime startDate = DateUtil.offsetDay(endDate, -29);
                QueryWrapper<YkfCustomerEntity> queryWrapper = new QueryWrapper<>();
                queryWrapper.lambda().ge(YkfCustomerEntity::getCreateTime, startDate)
                        .le(YkfCustomerEntity::getCreateTime, endDate);
                List<YkfCustomerEntity> list = ykfCustomerService.list(queryWrapper);
                if (null == list) {
                    list = new ArrayList<>();
                }
                while (startDate.compareTo(endDate) <= 0) {
                    DateTime finalStartDate = startDate;
                    long count = list.stream().filter(o -> StrUtil.equals(DateUtil.formatDate(finalStartDate), DateUtil.formatDate(o.getCreateTime()))).count();
                    Statistics3Model model = new Statistics3Model();
                    model.setDate(DateUtil.formatDate(startDate));
                    model.setValue(new BigDecimal(count));
                    resList.add(model);
                    startDate = DateUtil.offsetDay(startDate, 1);
                }
            } else if (StrUtil.equals(queryCycleType, "2")) {
                //近13周
                DateTime endDate = DateUtil.date();
                DateTime startDate = DateUtil.offsetWeek(endDate, -12);
                QueryWrapper<YkfCustomerEntity> queryWrapper = new QueryWrapper<>();
                queryWrapper.lambda().ge(YkfCustomerEntity::getCreateTime, startDate)
                        .le(YkfCustomerEntity::getCreateTime, endDate);
                List<YkfCustomerEntity> list = ykfCustomerService.list(queryWrapper);
                if (null == list) {
                    list = new ArrayList<>();
                }
                boolean flag = false;
                long lastValue = 0L;
                while (startDate.compareTo(endDate) <= 0) {
                    DateTime finalStartDate = startDate;
                    if (!flag) {
                        flag = true;
                        lastValue = list.stream().filter(o -> StrUtil.equals(DateUtil.formatDate(DateUtil.beginOfWeek(finalStartDate)), DateUtil.formatDate(DateUtil.beginOfWeek(o.getCreateTime())))).count();
                    } else {
                        long count = list.stream().filter(o -> StrUtil.equals(DateUtil.formatDate(DateUtil.beginOfWeek(finalStartDate)), DateUtil.formatDate(DateUtil.beginOfWeek(o.getCreateTime())))).count();
                        Statistics3Model model = new Statistics3Model();
                        model.setDate(DateUtil.formatDate(DateUtil.beginOfWeek(startDate)));
                        model.setValue(new BigDecimal(count));
                        if (lastValue == 0) {
                            if (count > 0) {
                                model.setQoq(new BigDecimal("100"));
                            } else {
                                model.setQoq(BigDecimal.ZERO);
                            }
                        } else {
                            //计算环比
                            BigDecimal value = new BigDecimal(count - lastValue).multiply(new BigDecimal(100)).divide(new BigDecimal(lastValue), 2, RoundingMode.HALF_UP);
                            model.setQoq(value);
                        }
                        resList.add(model);
                        startDate = DateUtil.offsetWeek(startDate, 1);
                        lastValue = count;
                    }

                }
            } else if (StrUtil.equals(queryCycleType, "3")) {
                //近12月
                DateTime endDate = DateUtil.date();
                DateTime startDate = DateUtil.offsetMonth(endDate, -11);
                DateTime startDate2 = DateUtil.offsetMonth(endDate, -23);
                QueryWrapper<YkfCustomerEntity> queryWrapper = new QueryWrapper<>();
                queryWrapper.lambda().ge(YkfCustomerEntity::getCreateTime, startDate2)
                        .le(YkfCustomerEntity::getCreateTime, endDate);
                List<YkfCustomerEntity> list = ykfCustomerService.list(queryWrapper);
                if (null == list) {
                    list = new ArrayList<>();
                }
                boolean flag = false;
                long lastValue = 0L;
                while (startDate.compareTo(endDate) <= 0) {
                    DateTime finalStartDate = startDate;
                    if (!flag) {
                        flag = true;
                        lastValue = list.stream().filter(o -> StrUtil.equals(DateUtil.formatDate(DateUtil.beginOfMonth(finalStartDate)), DateUtil.formatDate(DateUtil.beginOfMonth(o.getCreateTime())))).count();
                    } else {
                        long count = list.stream().filter(o -> StrUtil.equals(DateUtil.formatDate(DateUtil.beginOfMonth(finalStartDate)), DateUtil.formatDate(DateUtil.beginOfMonth(o.getCreateTime())))).count();
                        DateTime offset = DateUtil.offset(startDate, DateField.YEAR, -1);
                        long count2 = list.stream().filter(o -> StrUtil.equals(DateUtil.formatDate(DateUtil.beginOfMonth(offset)), DateUtil.formatDate(DateUtil.beginOfMonth(o.getCreateTime())))).count();

                        Statistics3Model model = new Statistics3Model();
                        model.setDate(DateUtil.format(startDate, "yyyy-MM"));
                        model.setValue(new BigDecimal(count));
                        if (lastValue == 0) {
                            if (count > 0) {
                                model.setQoq(new BigDecimal("100"));
                            } else {
                                model.setQoq(BigDecimal.ZERO);
                            }
                        } else {
                            //计算环比
                            BigDecimal value = new BigDecimal(count - lastValue).multiply(new BigDecimal(100)).divide(new BigDecimal(lastValue), 2, RoundingMode.HALF_UP);
                            model.setQoq(value);
                        }
                        if (count2 == 0) {
                            if (count > 0) {
                                model.setYoy(new BigDecimal("100"));
                            } else {
                                model.setYoy(BigDecimal.ZERO);
                            }
                        } else {
                            //计算同比
                            BigDecimal value = new BigDecimal(count - count2).multiply(new BigDecimal(100)).divide(new BigDecimal(count2), 2, RoundingMode.HALF_UP);
                            model.setYoy(value);
                        }
                        resList.add(model);
                        startDate = DateUtil.offsetMonth(startDate, 1);
                        lastValue = count;
                    }

                }
            } else if (StrUtil.equals(queryCycleType, "4")) {
                //近3年
                DateTime endDate = DateUtil.date();
                DateTime startDate = DateUtil.offset(endDate, DateField.YEAR, -2);
                QueryWrapper<YkfCustomerEntity> queryWrapper = new QueryWrapper<>();
                queryWrapper.lambda().ge(YkfCustomerEntity::getCreateTime, startDate)
                        .le(YkfCustomerEntity::getCreateTime, endDate);
                List<YkfCustomerEntity> list = ykfCustomerService.list(queryWrapper);
                if (null == list) {
                    list = new ArrayList<>();
                }
                boolean flag = false;
                long lastValue = 0L;
                while (startDate.compareTo(endDate) <= 0) {
                    DateTime finalStartDate = startDate;
                    if (!flag) {
                        flag = true;
                        lastValue = list.stream().filter(o -> StrUtil.equals(DateUtil.formatDate(DateUtil.beginOfYear(finalStartDate)), DateUtil.formatDate(DateUtil.beginOfYear(o.getCreateTime())))).count();
                    } else {
                        long count = list.stream().filter(o -> StrUtil.equals(DateUtil.formatDate(DateUtil.beginOfYear(finalStartDate)), DateUtil.formatDate(DateUtil.beginOfYear(o.getCreateTime())))).count();
                        Statistics3Model model = new Statistics3Model();
                        model.setDate(DateUtil.format(startDate, "yyyy"));
                        model.setValue(new BigDecimal(count));
                        if (lastValue == 0) {
                            if (count > 0) {
                                model.setQoq(new BigDecimal("100"));
                            } else {
                                model.setQoq(BigDecimal.ZERO);
                            }
                        } else {
                            //计算环比
                            BigDecimal value = new BigDecimal(count - lastValue).multiply(new BigDecimal(100)).divide(new BigDecimal(lastValue), 2, RoundingMode.HALF_UP);
                            model.setQoq(value);
                        }
                        resList.add(model);
                        startDate = DateUtil.offset(startDate, DateField.YEAR,1);
                        lastValue = count;
                    }

                }
            }
        }
        resList.sort(Comparator.comparing(Statistics3Model::getDate).reversed());
        return R.ok(resList);
    }

    /**
     * 流失客户
     */
    @PostMapping("/statistics4")
    public R statistics4(@RequestBody YkfStatisticsModel req) {
        List<Statistics3Model> resList = new ArrayList<>();
        List<YkfCustomerEntity> sourceList = new ArrayList<>();
        //查询所有流失客户
        QueryWrapper<YkfCustomerEntity> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.lambda().eq(YkfCustomerEntity::getCooperateStatus, 0);
        sourceList = ykfCustomerService.list(queryWrapper1);
//        List<Long> customerIds = list1.stream().map(YkfCustomerShopEntity::getCustomerId).distinct().collect(Collectors.toList());
//
//        QueryWrapper<YkfCustomerShopEntity> queryWrapper2 = new QueryWrapper<>();
//        queryWrapper2.lambda().eq(YkfCustomerShopEntity::getCooperateStatus, 1);
//        List<YkfCustomerShopEntity> list2 = ykfCustomerShopService.list(queryWrapper2);
//        if (ObjectUtil.isNotEmpty(list2)) {
//            List<Long> shopIds = new ArrayList<>();
//            for (YkfCustomerShopEntity shop : list2) {
//                if (!customerIds.contains(shop.getCustomerId()) && !shopIds.contains(shop.getShopId())) {
//                    shopIds.add(shop.getShopId());
//                }
//            }
//            if (shopIds.size() > 0) {
//                QueryWrapper<YkfCustomerShopEntity> queryWrapper = new QueryWrapper<>();
//                queryWrapper.lambda().in(YkfCustomerShopEntity::getShopId, shopIds)
//                        .orderByDesc(YkfCustomerShopEntity::getStopCooperateDate);
//                List<YkfCustomerShopEntity> list = ykfCustomerShopService.listByIds(shopIds);
//                List<Long> ids = new ArrayList<>();
//                for (YkfCustomerShopEntity shop : list) {
//                    if (!ids.contains(shop.getCustomerId())) {
//                        ids.add(shop.getCustomerId());
//                        sourceList.add(shop);
//                    }
//                }
//            }
//        }

        if (ObjectUtil.isNotEmpty(req) && ObjectUtil.isNotEmpty(req.getDateStart()) && ObjectUtil.isNotEmpty(req.getDateEnd())) {
            long count = sourceList.stream().filter(o -> DateUtil.compare(o.getStopCooperateDate(), req.getDateStart()) >= 0 && DateUtil.compare(o.getStopCooperateDate(), req.getDateEnd()) <= 0).count();
            Statistics3Model model = new Statistics3Model();
            model.setDate(DateUtil.formatDate(req.getDateStart()) + " 至 " + DateUtil.formatDate(req.getDateEnd()));
            model.setValue(new BigDecimal(count));
            resList.add(model);
        } else {
            String queryCycleType = req.getQueryCycleType();
            if (StrUtil.isBlank(queryCycleType)) {
                queryCycleType = "1";
            }
            if (StrUtil.equals(queryCycleType, "1")) {
                //近30天
                DateTime endDate = DateUtil.date();
                DateTime startDate = DateUtil.offsetDay(endDate, -29);
//                QueryWrapper<YkfCustomerEntity> queryWrapper = new QueryWrapper<>();
//                queryWrapper.lambda().ge(YkfCustomerEntity::getCreateTime, startDate)
//                        .le(YkfCustomerEntity::getCreateTime, endDate);
//                List<YkfCustomerEntity> list = ykfCustomerService.list(queryWrapper);
                DateTime finalStartDate1 = startDate;
                List<YkfCustomerEntity> list = sourceList.stream().filter(o -> DateUtil.compare(o.getStopCooperateDate(), finalStartDate1) >= 0 && DateUtil.compare(o.getStopCooperateDate(), endDate) <= 0).collect(Collectors.toList());
                if (null == list) {
                    list = new ArrayList<>();
                }
                while (startDate.compareTo(endDate) <= 0) {
                    DateTime finalStartDate = startDate;
                    long count = list.stream().filter(o -> StrUtil.equals(DateUtil.formatDate(finalStartDate), DateUtil.formatDate(o.getStopCooperateDate()))).count();
                    Statistics3Model model = new Statistics3Model();
                    model.setDate(DateUtil.formatDate(startDate));
                    model.setValue(new BigDecimal(count));
                    resList.add(model);
                    startDate = DateUtil.offsetDay(startDate, 1);
                }
            } else if (StrUtil.equals(queryCycleType, "2")) {
                //近13周
                DateTime endDate = DateUtil.date();
                DateTime startDate = DateUtil.offsetWeek(endDate, -12);
//                QueryWrapper<YkfCustomerEntity> queryWrapper = new QueryWrapper<>();
//                queryWrapper.lambda().ge(YkfCustomerEntity::getCreateTime, startDate)
//                        .le(YkfCustomerEntity::getCreateTime, endDate);
//                List<YkfCustomerEntity> list = ykfCustomerService.list(queryWrapper);
                DateTime finalStartDate1 = startDate;
                List<YkfCustomerEntity> list = sourceList.stream().filter(o -> DateUtil.compare(o.getStopCooperateDate(), finalStartDate1) >= 0 && DateUtil.compare(o.getStopCooperateDate(), endDate) <= 0).collect(Collectors.toList());

                if (null == list) {
                    list = new ArrayList<>();
                }
                boolean flag = false;
                long lastValue = 0L;
                while (startDate.compareTo(endDate) <= 0) {
                    DateTime finalStartDate = startDate;
                    if (!flag) {
                        flag = true;
                        lastValue = list.stream().filter(o -> StrUtil.equals(DateUtil.formatDate(DateUtil.beginOfWeek(finalStartDate)), DateUtil.formatDate(DateUtil.beginOfWeek(o.getStopCooperateDate())))).count();
                    } else {
                        long count = list.stream().filter(o -> StrUtil.equals(DateUtil.formatDate(DateUtil.beginOfWeek(finalStartDate)), DateUtil.formatDate(DateUtil.beginOfWeek(o.getStopCooperateDate())))).count();
                        Statistics3Model model = new Statistics3Model();
                        model.setDate(DateUtil.formatDate(DateUtil.beginOfWeek(startDate)));
                        model.setValue(new BigDecimal(count));
                        if (lastValue == 0) {
                            if (count > 0) {
                                model.setQoq(new BigDecimal("100"));
                            } else {
                                model.setQoq(BigDecimal.ZERO);
                            }
                        } else {
                            //计算环比
                            BigDecimal value = new BigDecimal(count - lastValue).multiply(new BigDecimal(100)).divide(new BigDecimal(lastValue), 2, RoundingMode.HALF_UP);
                            model.setQoq(value);
                        }
                        resList.add(model);
                        startDate = DateUtil.offsetWeek(startDate, 1);
                        lastValue = count;
                    }

                }
            } else if (StrUtil.equals(queryCycleType, "3")) {
                //近12月
                DateTime endDate = DateUtil.date();
                DateTime startDate = DateUtil.offsetMonth(endDate, -11);
                DateTime startDate2 = DateUtil.offsetMonth(endDate, -23);
//                QueryWrapper<YkfCustomerEntity> queryWrapper = new QueryWrapper<>();
//                queryWrapper.lambda().ge(YkfCustomerEntity::getCreateTime, startDate2)
//                        .le(YkfCustomerEntity::getCreateTime, endDate);
//                List<YkfCustomerEntity> list = ykfCustomerService.list(queryWrapper);
                DateTime finalStartDate1 = startDate;
                List<YkfCustomerEntity> list = sourceList.stream().filter(o -> DateUtil.compare(o.getStopCooperateDate(), finalStartDate1) >= 0 && DateUtil.compare(o.getStopCooperateDate(), endDate) <= 0).collect(Collectors.toList());

                if (null == list) {
                    list = new ArrayList<>();
                }
                boolean flag = false;
                long lastValue = 0L;
                while (startDate.compareTo(endDate) <= 0) {
                    DateTime finalStartDate = startDate;
                    if (!flag) {
                        flag = true;
                        lastValue = list.stream().filter(o -> StrUtil.equals(DateUtil.formatDate(DateUtil.beginOfMonth(finalStartDate)), DateUtil.formatDate(DateUtil.beginOfMonth(o.getStopCooperateDate())))).count();
                    } else {
                        long count = list.stream().filter(o -> StrUtil.equals(DateUtil.formatDate(DateUtil.beginOfMonth(finalStartDate)), DateUtil.formatDate(DateUtil.beginOfMonth(o.getStopCooperateDate())))).count();
                        DateTime offset = DateUtil.offset(startDate, DateField.YEAR, -1);
                        long count2 = list.stream().filter(o -> StrUtil.equals(DateUtil.formatDate(DateUtil.beginOfMonth(offset)), DateUtil.formatDate(DateUtil.beginOfMonth(o.getStopCooperateDate())))).count();

                        Statistics3Model model = new Statistics3Model();
                        model.setDate(DateUtil.format(startDate, "yyyy-MM"));
                        model.setValue(new BigDecimal(count));
                        if (lastValue == 0) {
                            if (count > 0) {
                                model.setQoq(new BigDecimal("100"));
                            } else {
                                model.setQoq(BigDecimal.ZERO);
                            }
                        } else {
                            //计算环比
                            BigDecimal value = new BigDecimal(count - lastValue).multiply(new BigDecimal(100)).divide(new BigDecimal(lastValue), 2, RoundingMode.HALF_UP);
                            model.setQoq(value);
                        }
                        if (count2 == 0) {
                            if (count > 0) {
                                model.setYoy(new BigDecimal("100"));
                            } else {
                                model.setYoy(BigDecimal.ZERO);
                            }
                        } else {
                            //计算同比
                            BigDecimal value = new BigDecimal(count - count2).multiply(new BigDecimal(100)).divide(new BigDecimal(count2), 2, RoundingMode.HALF_UP);
                            model.setYoy(value);
                        }
                        resList.add(model);
                        startDate = DateUtil.offsetMonth(startDate, 1);
                        lastValue = count;
                    }

                }
            } else if (StrUtil.equals(queryCycleType, "4")) {
                //近3年
                DateTime endDate = DateUtil.date();
                DateTime startDate = DateUtil.offset(endDate, DateField.YEAR, -2);
//                QueryWrapper<YkfCustomerEntity> queryWrapper = new QueryWrapper<>();
//                queryWrapper.lambda().ge(YkfCustomerEntity::getCreateTime, startDate)
//                        .le(YkfCustomerEntity::getCreateTime, endDate);
//                List<YkfCustomerEntity> list = ykfCustomerService.list(queryWrapper);
                DateTime finalStartDate1 = startDate;
                List<YkfCustomerEntity> list = sourceList.stream().filter(o -> DateUtil.compare(o.getStopCooperateDate(), finalStartDate1) >= 0 && DateUtil.compare(o.getStopCooperateDate(), endDate) <= 0).collect(Collectors.toList());

                if (null == list) {
                    list = new ArrayList<>();
                }
                boolean flag = false;
                long lastValue = 0L;
                while (startDate.compareTo(endDate) <= 0) {
                    DateTime finalStartDate = startDate;
                    if (!flag) {
                        flag = true;
                        lastValue = list.stream().filter(o -> StrUtil.equals(DateUtil.formatDate(DateUtil.beginOfYear(finalStartDate)), DateUtil.formatDate(DateUtil.beginOfYear(o.getStopCooperateDate())))).count();
                    } else {
                        long count = list.stream().filter(o -> StrUtil.equals(DateUtil.formatDate(DateUtil.beginOfYear(finalStartDate)), DateUtil.formatDate(DateUtil.beginOfYear(o.getStopCooperateDate())))).count();
                        Statistics3Model model = new Statistics3Model();
                        model.setDate(DateUtil.format(startDate, "yyyy"));
                        model.setValue(new BigDecimal(count));
                        if (lastValue == 0) {
                            if (count > 0) {
                                model.setQoq(new BigDecimal("100"));
                            } else {
                                model.setQoq(BigDecimal.ZERO);
                            }
                        } else {
                            //计算环比
                            BigDecimal value = new BigDecimal(count - lastValue).multiply(new BigDecimal(100)).divide(new BigDecimal(lastValue), 2, RoundingMode.HALF_UP);
                            model.setQoq(value);
                        }
                        resList.add(model);
                        startDate = DateUtil.offset(startDate, DateField.YEAR,1);
                        lastValue = count;
                    }

                }
            }
        }
        resList.sort(Comparator.comparing(Statistics3Model::getDate).reversed());
        return R.ok(resList);
    }

    /**
     * 新增客户
     */
    @PostMapping("/statistics5")
    public R statistics5(@RequestBody YkfStatisticsModel req) {
        List<Statistics3Model> resList = new ArrayList<>();
        if (ObjectUtil.isNotEmpty(req) && ObjectUtil.isNotEmpty(req.getDateStart()) && ObjectUtil.isNotEmpty(req.getDateEnd())) {
            QueryWrapper<YkfCustomerConsultEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().ge(YkfCustomerConsultEntity::getCreateTime, req.getDateStart())
                    .le(YkfCustomerConsultEntity::getCreateTime, req.getDateEnd());
            int count = consultService.count(queryWrapper);
            Statistics3Model model = new Statistics3Model();
            model.setDate(DateUtil.formatDate(req.getDateStart()) + " 至 " + DateUtil.formatDate(req.getDateEnd()));
            model.setValue(new BigDecimal(count));
            resList.add(model);
        } else {
            String customerStatus = "";
            String type = req.getType();
            switch (type) {
                case "1":
                    customerStatus = "初步接触";
                    break;
                case "2":
                    customerStatus = "持续跟进";
                    break;
                case "3":
                    customerStatus = "无效客户";
                    break;
                case "4":
                    customerStatus = "成交客户";
                    break;
            }
            String queryCycleType = req.getQueryCycleType();
            if (StrUtil.isBlank(queryCycleType)) {
                queryCycleType = "1";
            }
            if (StrUtil.equals(queryCycleType, "1")) {
                //近30天
                DateTime endDate = DateUtil.date();
                DateTime startDate = DateUtil.offsetDay(endDate, -29);
                QueryWrapper<YkfCustomerConsultEntity> queryWrapper = new QueryWrapper<>();
                queryWrapper.lambda().ge(YkfCustomerConsultEntity::getCreateTime, startDate)
                        .le(YkfCustomerConsultEntity::getCreateTime, endDate);
                if (StrUtil.isNotBlank(customerStatus)) {
                    queryWrapper.lambda().eq(YkfCustomerConsultEntity::getCustomerStatus, customerStatus);
                }
                List<YkfCustomerConsultEntity> list = consultService.list(queryWrapper);
                if (null == list) {
                    list = new ArrayList<>();
                }
                while (startDate.compareTo(endDate) <= 0) {
                    DateTime finalStartDate = startDate;
                    long count = list.stream().filter(o -> StrUtil.equals(DateUtil.formatDate(finalStartDate), DateUtil.formatDate(o.getCreateTime()))).count();
                    Statistics3Model model = new Statistics3Model();
                    model.setDate(DateUtil.formatDate(startDate));
                    model.setValue(new BigDecimal(count));
                    resList.add(model);
                    startDate = DateUtil.offsetDay(startDate, 1);
                }
            } else if (StrUtil.equals(queryCycleType, "2")) {
                //近13周
                DateTime endDate = DateUtil.date();
                DateTime startDate = DateUtil.offsetWeek(endDate, -12);
                QueryWrapper<YkfCustomerConsultEntity> queryWrapper = new QueryWrapper<>();
                queryWrapper.lambda().ge(YkfCustomerConsultEntity::getCreateTime, startDate)
                        .le(YkfCustomerConsultEntity::getCreateTime, endDate);
                if (StrUtil.isNotBlank(customerStatus)) {
                    queryWrapper.lambda().eq(YkfCustomerConsultEntity::getCustomerStatus, customerStatus);
                }
                List<YkfCustomerConsultEntity> list = consultService.list(queryWrapper);
                if (null == list) {
                    list = new ArrayList<>();
                }
                boolean flag = false;
                long lastValue = 0L;
                while (startDate.compareTo(endDate) <= 0) {
                    DateTime finalStartDate = startDate;
                    if (!flag) {
                        flag = true;
                        lastValue = list.stream().filter(o -> StrUtil.equals(DateUtil.formatDate(DateUtil.beginOfWeek(finalStartDate)), DateUtil.formatDate(DateUtil.beginOfWeek(o.getCreateTime())))).count();
                    } else {
                        long count = list.stream().filter(o -> StrUtil.equals(DateUtil.formatDate(DateUtil.beginOfWeek(finalStartDate)), DateUtil.formatDate(DateUtil.beginOfWeek(o.getCreateTime())))).count();
                        Statistics3Model model = new Statistics3Model();
                        model.setDate(DateUtil.formatDate(DateUtil.beginOfWeek(startDate)));
                        model.setValue(new BigDecimal(count));
                        if (lastValue == 0) {
                            if (count > 0) {
                                model.setQoq(new BigDecimal("100"));
                            } else {
                                model.setQoq(BigDecimal.ZERO);
                            }
                        } else {
                            //计算环比
                            BigDecimal value = new BigDecimal(count - lastValue).multiply(new BigDecimal(100)).divide(new BigDecimal(lastValue), 2, RoundingMode.HALF_UP);
                            model.setQoq(value);
                        }
                        resList.add(model);
                        startDate = DateUtil.offsetWeek(startDate, 1);
                        lastValue = count;
                    }

                }
            } else if (StrUtil.equals(queryCycleType, "3")) {
                //近12月
                DateTime endDate = DateUtil.date();
                DateTime startDate = DateUtil.offsetMonth(endDate, -11);
                DateTime startDate2 = DateUtil.offsetMonth(endDate, -23);
                QueryWrapper<YkfCustomerConsultEntity> queryWrapper = new QueryWrapper<>();
                queryWrapper.lambda().ge(YkfCustomerConsultEntity::getCreateTime, startDate2)
                        .le(YkfCustomerConsultEntity::getCreateTime, endDate);
                if (StrUtil.isNotBlank(customerStatus)) {
                    queryWrapper.lambda().eq(YkfCustomerConsultEntity::getCustomerStatus, customerStatus);
                }
                List<YkfCustomerConsultEntity> list = consultService.list(queryWrapper);
                if (null == list) {
                    list = new ArrayList<>();
                }
                boolean flag = false;
                long lastValue = 0L;
                while (startDate.compareTo(endDate) <= 0) {
                    DateTime finalStartDate = startDate;
                    if (!flag) {
                        flag = true;
                        lastValue = list.stream().filter(o -> StrUtil.equals(DateUtil.formatDate(DateUtil.beginOfMonth(finalStartDate)), DateUtil.formatDate(DateUtil.beginOfMonth(o.getCreateTime())))).count();
                    } else {
                        long count = list.stream().filter(o -> StrUtil.equals(DateUtil.formatDate(DateUtil.beginOfMonth(finalStartDate)), DateUtil.formatDate(DateUtil.beginOfMonth(o.getCreateTime())))).count();
                        DateTime offset = DateUtil.offset(startDate, DateField.YEAR, -1);
                        long count2 = list.stream().filter(o -> StrUtil.equals(DateUtil.formatDate(DateUtil.beginOfMonth(offset)), DateUtil.formatDate(DateUtil.beginOfMonth(o.getCreateTime())))).count();

                        Statistics3Model model = new Statistics3Model();
                        model.setDate(DateUtil.format(startDate, "yyyy-MM"));
                        model.setValue(new BigDecimal(count));
                        if (lastValue == 0) {
                            if (count > 0) {
                                model.setQoq(new BigDecimal("100"));
                            } else {
                                model.setQoq(BigDecimal.ZERO);
                            }
                        } else {
                            //计算环比
                            BigDecimal value = new BigDecimal(count - lastValue).multiply(new BigDecimal(100)).divide(new BigDecimal(lastValue), 2, RoundingMode.HALF_UP);
                            model.setQoq(value);
                        }
                        if (count2 == 0) {
                            if (count > 0) {
                                model.setYoy(new BigDecimal("100"));
                            } else {
                                model.setYoy(BigDecimal.ZERO);
                            }
                        } else {
                            //计算同比
                            BigDecimal value = new BigDecimal(count - count2).multiply(new BigDecimal(100)).divide(new BigDecimal(count2), 2, RoundingMode.HALF_UP);
                            model.setYoy(value);
                        }
                        resList.add(model);
                        startDate = DateUtil.offsetMonth(startDate, 1);
                        lastValue = count;
                    }

                }
            } else if (StrUtil.equals(queryCycleType, "4")) {
                //近3年
                DateTime endDate = DateUtil.date();
                DateTime startDate = DateUtil.offset(endDate, DateField.YEAR, -2);
                QueryWrapper<YkfCustomerConsultEntity> queryWrapper = new QueryWrapper<>();
                queryWrapper.lambda().ge(YkfCustomerConsultEntity::getCreateTime, startDate)
                        .le(YkfCustomerConsultEntity::getCreateTime, endDate);
                if (StrUtil.isNotBlank(customerStatus)) {
                    queryWrapper.lambda().eq(YkfCustomerConsultEntity::getCustomerStatus, customerStatus);
                }
                List<YkfCustomerConsultEntity> list = consultService.list(queryWrapper);
                if (null == list) {
                    list = new ArrayList<>();
                }
                boolean flag = false;
                long lastValue = 0L;
                while (startDate.compareTo(endDate) <= 0) {
                    DateTime finalStartDate = startDate;
                    if (!flag) {
                        flag = true;
                        lastValue = list.stream().filter(o -> StrUtil.equals(DateUtil.formatDate(DateUtil.beginOfYear(finalStartDate)), DateUtil.formatDate(DateUtil.beginOfYear(o.getCreateTime())))).count();
                    } else {
                        long count = list.stream().filter(o -> StrUtil.equals(DateUtil.formatDate(DateUtil.beginOfYear(finalStartDate)), DateUtil.formatDate(DateUtil.beginOfYear(o.getCreateTime())))).count();
                        Statistics3Model model = new Statistics3Model();
                        model.setDate(DateUtil.format(startDate, "yyyy"));
                        model.setValue(new BigDecimal(count));
                        if (lastValue == 0) {
                            if (count > 0) {
                                model.setQoq(new BigDecimal("100"));
                            } else {
                                model.setQoq(BigDecimal.ZERO);
                            }
                        } else {
                            //计算环比
                            BigDecimal value = new BigDecimal(count - lastValue).multiply(new BigDecimal(100)).divide(new BigDecimal(lastValue), 2, RoundingMode.HALF_UP);
                            model.setQoq(value);
                        }
                        resList.add(model);
                        startDate = DateUtil.offset(startDate, DateField.YEAR,1);
                        lastValue = count;
                    }

                }
            }
        }
        resList.sort(Comparator.comparing(Statistics3Model::getDate).reversed());
        return R.ok(resList);
    }
}
